import React from "react";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { Database, FileText, ExternalLink } from "lucide-react";
import { color } from "../../theme/colors";
import { spacing } from "../../theme/spacing";

const ChipContainer = styled.span<{ $type: "corpus" | "document" }>`
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px 2px 6px;
  border-radius: 4px;
  font-size: 0.9em;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s ease;
  vertical-align: middle;
  margin: 0 2px;

  background: ${(props) =>
    props.$type === "corpus"
      ? "linear-gradient(135deg, #667eea15 0%, #764ba215 100%)"
      : "linear-gradient(135deg, #f093fb15 0%, #f5576c15 100%)"};

  border: 1px solid
    ${(props) => (props.$type === "corpus" ? color.P4 : "#f5576c40")};

  color: ${(props) => (props.$type === "corpus" ? color.P8 : "#c41e3a")};

  &:hover {
    background: ${(props) =>
      props.$type === "corpus"
        ? "linear-gradient(135deg, #667eea25 0%, #764ba225 100%)"
        : "linear-gradient(135deg, #f093fb25 0%, #f5576c25 100%)"};

    border-color: ${(props) =>
      props.$type === "corpus" ? color.P6 : "#f5576c80"};

    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }

  &:active {
    transform: translateY(0);
  }
`;

const IconWrapper = styled.span`
  display: flex;
  align-items: center;
  justify-content: center;
`;

const ChipText = styled.span`
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;

  @media (max-width: 640px) {
    max-width: 120px;
  }
`;

const ExternalIcon = styled(ExternalLink)`
  opacity: 0.6;
  flex-shrink: 0;
`;

export interface MentionedResource {
  type: "CORPUS" | "DOCUMENT";
  id: string;
  slug: string;
  title: string;
  url: string;
  corpus?:
    | {
        slug: string;
        title: string;
      }
    | null
    | undefined;
}

export interface MentionChipProps {
  resource: MentionedResource;
  /** Optional callback instead of default navigation */
  onClick?: (resource: MentionedResource) => void;
}

/**
 * Clickable chip for rendering @ mentions of corpuses and documents
 * Backend provides the URL via the mentionedResources field
 *
 * Security: URLs are generated by backend with proper permission checks
 * Navigation uses React Router for corpus (full page) or custom handler for document (sidebar)
 *
 * Part of Issue #623 - @ Mentions Feature
 */
export function MentionChip({ resource, onClick }: MentionChipProps) {
  const navigate = useNavigate();

  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();

    if (onClick) {
      onClick(resource);
      return;
    }

    // Default navigation behavior
    if (resource.type === "CORPUS") {
      // Navigate to corpus page (full page view)
      navigate(resource.url);
    } else if (resource.type === "DOCUMENT") {
      // For documents, navigate to URL (which includes the document view)
      navigate(resource.url);
    }
  };

  const icon =
    resource.type === "CORPUS" ? (
      <Database size={14} />
    ) : (
      <FileText size={14} />
    );

  return (
    <ChipContainer
      $type={resource.type === "CORPUS" ? "corpus" : "document"}
      onClick={handleClick}
      title={`${resource.title}${
        resource.corpus ? ` (in ${resource.corpus.title})` : ""
      }`}
      role="link"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          handleClick(e as any);
        }
      }}
    >
      <IconWrapper>{icon}</IconWrapper>
      <ChipText>{resource.title}</ChipText>
      <ExternalIcon size={12} />
    </ChipContainer>
  );
}

/**
 * Parse message content and replace mention patterns with MentionChip components
 * Looks for patterns like @corpus:slug, @document:slug, @corpus:slug/document:slug
 *
 * @param content - HTML content from message
 * @param mentionedResources - Array of mentioned resources from backend
 * @returns React element with mentions replaced by chips
 */
export function parseMentionsInContent(
  content: string,
  mentionedResources: MentionedResource[]
): React.ReactNode {
  if (!mentionedResources || mentionedResources.length === 0) {
    // No mentions, return content as-is
    return <div dangerouslySetInnerHTML={{ __html: content }} />;
  }

  // Create a map of mention patterns to resources
  const mentionMap = new Map<string, MentionedResource>();

  mentionedResources.forEach((resource) => {
    if (resource.type === "CORPUS") {
      mentionMap.set(`@corpus:${resource.slug}`, resource);
    } else if (resource.type === "DOCUMENT") {
      if (resource.corpus) {
        mentionMap.set(
          `@corpus:${resource.corpus.slug}/document:${resource.slug}`,
          resource
        );
      } else {
        mentionMap.set(`@document:${resource.slug}`, resource);
      }
    }
  });

  // Split content by mention patterns and rebuild with chips
  // This is a simplified version - for production, use a proper HTML parser
  const mentionRegex =
    /@(?:corpus:[a-z0-9-]+(?:\/document:[a-z0-9-]+)?|document:[a-z0-9-]+)/gi;

  const parts: React.ReactNode[] = [];
  let lastIndex = 0;
  let match;
  let key = 0;

  while ((match = mentionRegex.exec(content)) !== null) {
    // Add text before mention
    if (match.index > lastIndex) {
      parts.push(
        <span
          key={`text-${key++}`}
          dangerouslySetInnerHTML={{
            __html: content.substring(lastIndex, match.index),
          }}
        />
      );
    }

    // Add mention chip
    const mentionText = match[0];
    const resource = mentionMap.get(mentionText);

    if (resource) {
      parts.push(<MentionChip key={`mention-${key++}`} resource={resource} />);
    } else {
      // Mention not found in resources (user doesn't have permission)
      // Just render as plain text
      parts.push(<span key={`text-${key++}`}>{mentionText}</span>);
    }

    lastIndex = mentionRegex.lastIndex;
  }

  // Add remaining text
  if (lastIndex < content.length) {
    parts.push(
      <span
        key={`text-${key++}`}
        dangerouslySetInnerHTML={{ __html: content.substring(lastIndex) }}
      />
    );
  }

  return <div>{parts}</div>;
}
